package com.example.springbootelasticsearch.service;

import com.alibaba.fastjson.JSON;
import com.example.springbootelasticsearch.config.ElasticSearchClientConfig;
import com.example.springbootelasticsearch.pojo.Content;
import com.example.springbootelasticsearch.uitl.HtmlParseUtil;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.query.WildcardQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.swing.text.Highlighter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class ContentService {

    @Resource(name = "restHighLevelClient")
    private RestHighLevelClient client;

//    public static void main(String[] args) throws IOException {
//        //1.解析数据放到es索引中
//        ContentService service = new ContentService();
//        service.parseContent("java");
//
//        //2. 从es中查询数据
////        List<Map<String, Object>> result = service.searchPage("java", 0, 2);
////        for (Map<String, Object> map : result) {
////            for (String key : map.keySet()) {
////                System.out.println(map.get(key));
////            }
////        }
//    }

    //1.解析数据放到es索引中
    public Boolean parseContent() throws IOException {
        List<Content> contents = new ArrayList<>();
        Content content1 = new Content("牙膏", "www.baidu.com", "12");
        Content content2 = new Content("牙膏", "www.baidu.com", "12");
        Content content3 = new Content("牙膏", "www.baidu.com", "12");
        contents.add(content1);
        contents.add(content2);
        contents.add(content3);

        //把查询出来的数据放到es索引中
        BulkRequest request = new BulkRequest();
        request.timeout("4m");
        for (int i = 0; i < contents.size(); i++) {
            request.add(new IndexRequest("jd_goods2").source(JSON.toJSONString(contents.get(i)), XContentType.JSON));
        }
        BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
        return !response.hasFailures();
    }

    //2. 在索引中进行搜索
    public List<Map<String, Object>> searchPage(String keyword, int pageNo, int pageSize) throws IOException {
        if (pageNo < 1) {
            pageNo = 1;
        }
        //条件搜索
        SearchRequest request = new SearchRequest("jd_goods");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        //分页查询
        builder.from(pageNo);
        builder.size(pageSize);
        //精准匹配查询
//        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", "*" + keyword + "*");
//        builder.query(termQueryBuilder);
//        builder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        //分词查询
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("title", keyword).analyzer("standard");
        builder.query(matchQueryBuilder);
        builder.timeout(new TimeValue(60, TimeUnit.SECONDS));
//        //模糊查询
//        WildcardQueryBuilder wildBuilder = QueryBuilders.wildcardQuery("title", "*" + keyword + "*");
//        builder.query(wildBuilder);
        //高亮查询
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.requireFieldMatch(false); //意思是不需要有多个字段高亮
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        builder.highlighter(highlightBuilder);
        //执行查询
        request.source(builder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        //对查询结果进行封装
        List<Map<String, Object>> list = new ArrayList<>();
        for (SearchHit hit : response.getHits().getHits()) {

            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField title = highlightFields.get("title");
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            //解析高亮字段,原理就是将原来的字段换为我们高亮的字段即可
            if (title != null) {
                Text[] fragments = title.getFragments();
                String n_title = "";
                for (Text text : fragments) {
                    n_title += text;
                }
                sourceAsMap.put("title", n_title);  //高亮字段替换掉原来的字段
            }
            list.add(sourceAsMap);
        }
        return list;
    }
}
